var tsarr = new Array();//房间数量数组
function MathJ()
{
    if(parseInt($('#txtQty7').val())>1){

        $('#txtQty7').val(parseInt($('#txtQty7').val())-1);
        $('#saleprice').text(parseFloat($('#txtQty7').val())*parseFloat($('#sale_price').val()).toFixed(2));
    }
}
function MathAdd()
{
    if(parseInt($('#txtQty7').val())<tsarr[0]){
        $('#txtQty7').val(parseInt($('#txtQty7').val())+1);
        $('#saleprice').text(parseFloat($('#txtQty7').val())*parseFloat($('#sale_price').val()).toFixed(2));


    }
    else{
        alert("没有那么多房间");
    }
}
//计算天数差的函数，通用
function  DateDiff(sDate1,  sDate2){    //sDate1和sDate2是2006-12-18格式
    var  aDate,  oDate1,  oDate2,  iDays;
    aDate  =  sDate1.split("-")  ;
    //oDate1  =  new  Date(aDate[1]  +  '-'  +  aDate[2]  +  '-'  +  aDate[0]) ;   //转换为12-18-2006格式
    oDate1= new Date(aDate[0], aDate[1] - 1, aDate[2],0,0,0);

    aDate  =  sDate2.split("-")  ;
    //oDate2  =  new  Date(aDate[1]  +  '-'  +  aDate[2]  +  '-'  +  aDate[0])  ;
    oDate2= new Date(aDate[0], aDate[1] - 1, aDate[2],0,0,0);
    iDays  =  parseInt(Math.abs(oDate1  -  oDate2)  /  1000  /  60  /  60  /24) ;   //把相差的毫秒数转换为天数
    //alert(aDate[1]+"|||"+aDate[2]+"|||"+aDate[0]+"|||"+oDate2+"|||"+iDays);
    return  iDays+1;
}

var calendar = function (year, month) {
    var date = null;
    if (arguments.length == 2) {
        date = this.parseISO8601(year + "-" + (month.toString().length == 1 ? ("0" + month) : month) + "-01");
    } else {
        date = new Date();
    }
    this.init(date);
};
calendar.prototype = {
    WeekShow: ["日", "一", "二", "三", "四", "五", "六"],
    container: "",
    init: function (date) {
        this.NowDate = date;
    },
    toString: function () {
        var month = this.NowDate.getMonth() + 1;
        var days = this.NowDate.getDate();
        if (month.length == 1) {
            month = "0" + month;
        }
        if (days.length == 1) {
            days = "0" + days;
        }
        return this.NowDate.getFullYear() + "年" + month.toString() + "月";
    },
    DayArray: new Array(),
    theadHtml: function () {
        var thead = $("<thead></thead>");
        var tr = $("<tr></tr>");
        thead.append(tr);
        for (i in this.WeekShow) {
            tr.append($("<th></th>").text(this.WeekShow[i]));
        }
        return thead;
    },
    renderMonth: function (callback) {
        if (typeof callback == "function") {
            this._renderMonth = callback;
        }

    },
    render: function (callback) {
        if (this.NowDate == "Invalid Date") {
            return;
        }
        var table = $("<table></table>").addClass("calendar");
        var tbody = $("<tbody></tbody>");
        table.append(this.theadHtml());
        var tr = $("<tr></tr>");
        this.DayArray.length = 0;

        var lastDay = this.MonthLastDay();
        this.NowDate.setDate(1);
        var year = this.NowDate.getFullYear();
        var month = this.NowDate.getMonth() + 1;
        if (month.toString().length == 1) {
            month = "0" + month;
        }
        var fristDayWeek = this.NowDate.getDay();
        if (fristDayWeek == 0) {
            fristDayWeek = 7;
        } else {
            for (i = 0; i < fristDayWeek; i++) {
                tr.append($("<td></td>").html("&nbsp;"));
            }
        }
        for (i = 1; i <= lastDay; i++) {
            var eachDate = this.parseISO8601(year + "-" + month + "-" + (i.toString().length == 1 ? ("0" + i) : i));
            var week = eachDate.getDay();
            if (week == 0) {
                week = 7;
            }
            if (week == 7) {//周日
                tr = $("<tr></tr>");
            }
            var td = $("<td></td>").attr("date", year + "-" + month + "-" + (i.toString().length == 1 ? ("0" + i) : i));
            this.DayArray.push(td);
            tr.append(td);
            if (week == 6) {//周六
                tbody.append(tr);
            }
        }
        var lastDayWeek = this.parseISO8601(year + "-" + month + "-" + (lastDay.toString().length == 1 ? ("0" + lastDay) : lastDay)).getDay();
        if (lastDayWeek != 6) {
            for (i = 0; i < 6 - lastDayWeek; i++) {
                tr.append($("<td></td>").html("&nbsp;"));
            }
            tbody.append(tr);
        }
        table.append(tbody);
        $(document.getElementById(this.container)).empty().append(table);
        if (this.renderEvent && typeof this.renderEvent == "function") {
            for (idx in this.DayArray)
                this.renderEvent.call(this.DayArray[idx], this.parseISO8601(this.DayArray[idx].attr("date")));
        } else if (typeof callback == "function") {
            if (!this.renderEvent) {
                this.renderEvent = callback;
            }
            for (idx in this.DayArray)
                callback.call(this.DayArray[idx], this.parseISO8601(this.DayArray[idx].attr("date")));
        }
        if (typeof this._renderMonth == "function") {
            this._renderMonth.call(this, this.toString());
        }

    },
    MonthLastDay: function () {
        var currentMonth = this.NowDate.getMonth();
        var nextMonth = ++currentMonth;
        var nextMonthFirstDay = new Date(this.NowDate.getFullYear(), nextMonth, 1);
        var oneDay = 1000 * 60 * 60 * 24;
        return new Date(nextMonthFirstDay - oneDay).getDate();
    },
    prevMonth: function (callback) {
        this.NowDate = this.DateAdd('m', -1, this.NowDate);
        this.render(callback);
    },
    nextMonth: function (callback) {
        this.NowDate = this.DateAdd('m', 1, this.NowDate);
        this.render(callback);
    },
    changeDate: function (year, month, callback) {
        this.NowDate = this.parseISO8601(year + "-" + month + "-01");
        this.render(callback);
    },
    select: function (date) {
        for (idx = 0, len = this.DayArray.length; idx < len; idx++) {
            if (date == this.DayArray[idx].attr("date")) {
                return this.DayArray[idx];
            }
        }
        return null;
    },
    parseISO8601: function (dateStringInRange) {
        var isoExp = /^\s*(\d{4})-(\d\d)-(\d\d)\s*$/,
            date = new Date(NaN), month,
            parts = isoExp.exec(dateStringInRange);

        if (parts) {
            month = +parts[2];
            date.setFullYear(parts[1], month - 1, parts[3]);
            if (month != date.getMonth() + 1) {
                date.setTime(NaN);
            }
        }
        return date;
    },
    DateAdd: function (strInterval, NumDay, dtDate) {
        var dtTmp = new Date(dtDate);
        if (isNaN(dtTmp)) dtTmp = new Date();
        switch (strInterval) {
            case "s":
                dtTmp = new Date(Date.parse(dtTmp) + (1000 * parseInt(NumDay)));
                break;
            case "n":
                dtTmp = new Date(Date.parse(dtTmp) + (60000 * parseInt(NumDay)));
                break;
            case "h":
                dtTmp = new Date(Date.parse(dtTmp) + (3600000 * parseInt(NumDay)));
                break;
            case "d":
                dtTmp = new Date(Date.parse(dtTmp) + (86400000 * parseInt(NumDay)));
                break;
            case "w":
                dtTmp = new Date(Date.parse(dtTmp) + ((86400000 * 7) * parseInt(NumDay)));
                break;
            case "m":
                dtTmp = new Date(dtTmp.getFullYear(), (dtTmp.getMonth()) + parseInt(NumDay), dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds());
                break;
            case "y":
                dtTmp = new Date(dtTmp.getFullYear() + parseInt(NumDay), dtTmp.getMonth(), dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds());
                break;

        }
        return dtTmp;

    }

};



var cal = new calendar();
//cal.WeekShow = ["星期天", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
cal.renderMonth(function (date) {
    $("#MonthShow").html(date);
});
cal.container = "calShow";



var jsonDate =rel;  //alert(jsonDate);
var dateNow = new Date();
dateNow = dateNow.getFullYear().toString() + dateNow.getMonth().toString() + dateNow.getDate().toString();
window.onload = function () {
    cal.render(function (day) {
        var $this = this;
        if (dateNow == (day.getFullYear().toString() + day.getMonth().toString() + day.getDate().toString())) {
            //$this.addClass("today").html(day.getDate());
        } else
            $this.hover(function () {
                //$(this).addClass("today1");
            }, function () {
                //$(this).removeClass("today1");

            }).html(day.getDate());
    });
    var ti =0;//计数标识第一次选取不做判断
    var fn = function () {
        for (i in jsonDate) {
            var data = jsonDate[i];
            var query = cal.select(data.Date);
            if (query) {
                var html = new Array();

                // html.push("销售日期:" + data.Date + "<br />");
                // html.push("过期时间:" + data.ExpireDate + "<br />");
                html.push("<span class='day'>" + parseInt(query.attr("date").split('-')[2]) + " </span ><br />");
                // html.push("市场价:" + data.MarketPrice + "<br />");
                html.push("<span class='pric'>" + "&yen;" + data.SalePrice + " </span ><br />");
                html.push("<span class='num'>" + data.Quantity + "间" + " </span ><br />");

                query.click(function () {
                    if($(this).attr("class")=="today"){//判断是否已经选择
                        if(ti==1){//判断是否只剩一个
                            $(this).attr("class","");
                            ti = ti - 1;
                            return;
                        }
                        var index = parseInt($.trim($(this).find('span.day').text()));//获取当前的日期
                        //if(($('table.calendar').find('td').eq(index).attr("class") != "today" && $('table.calendar').find('td').eq(index-2).attr("class") == "today") || ($('table.calendar').find('td').eq(index).attr("class") == "today" && $('table.calendar').find('td').eq(index-2).attr("class") != "today")){
                        $(this).attr("class","");
                        ti = ti - 1;
                        //}else{
                        //	alert("不能隔天预定房间，如有需要请分俩次预定"); return false;
                        //}
                    }else{
                        if($.trim($(this).find('span.num').text())=='0间'){
                            alert('这一天没有剩余房间');
                        }else{
                            if(ti==0){//判断是否第一个选择
                                $(this).attr("class","today");
                                ti = ti + 1;
                            }else{
                                var index = parseInt($.trim($(this).find('span.day').text()));//获取当前的日期
                                //if($('table.calendar').find('td').eq(index).attr("class") == "today" || $('table.calendar').find('td').eq(index-2).attr("class") == "today"){//判断是否隔天选取
                                $(this).attr("class","today");
                                ti = ti + 1;
                                //}else{
                                //alert("不能隔天预定房间，如有需要请分俩次预定");
                                //}
                            }
                        }
                    }
                }).html(html.join(""));
            }
        }
    }

    $('.month').append("<a href='javascript:;' id='monthok'>确定</a>");

    fn();
    $("#prevMonth").click(function () {
        //$.ajax();
        cal.prevMonth();

        fn();
    });

    $("#nextMonth").click(function () {
        cal.nextMonth();

        fn();
    });


    $(document).ready(function () {
        var ps = $("#SaleDate").position();
        $(".month").css("position", "absolute");
        $(".month").css("left", ps.left - 0); //距离左边距
        $(".month").css("top", ps.top - 0); //距离上边距
        $("#SaleDate").click(function () {
            $(".month").show();
        });
        $("#monthok").click(function () {
            var ydsj = new Array();//时间数组
            var sjc = new Array();//时间戳数组
            var i = 0;//数组下标
            var totalPri=0;//总价
            var isok=true;

            $('table.calendar').find('td').each(function(index, element) {//循环table下所有td
                if($(this).attr("class")=="today"){//判断是否被选中
                    ydsj[i] = $(this).attr('date').replace(/-/g,'/');//转化时间格式
                    var date = new Date(ydsj[i]);//时间转时间戳

                    sjc[i]=date.getTime();//时间戳存数入组
                    ydsj[i] = ydsj[i].replace('/','-').replace('/','-');//时间格式转化

                    if(i<($('table.calendar').find('td.today').length-1)){
                        var prics=$.trim($(this).find('span.pric').text()).substring(1,$.trim($(this).find('span.pric').text()).length);
                        totalPri=parseFloat(prics)+parseFloat(totalPri);
                    }

                    //var total=$('#orderTotal').text();
                    //var totalPrice=parseFloat($('#num').val()*prics)+parseFloat(total);
                    //$('#orderTotal').text(totalPrice);




                    $('#dayNum').html("(共"+(ydsj.length-1)+"晚)");

                    //存入选中的房间数量
                    var fangNum=$.trim($(this).find('span.num').text()).substring(0,$.trim($(this).find('span.num').text()).length-1);
                    $('#days').val(fangNum);
                    if(fangNum<parseInt($("#txtQty7").val())){
                        alert("选购数量超过库存"+parseInt($(this).find('span.num').text())+"，请重选");                        isok=false;
                        return false;
                    }
                    tsarr[i] = fangNum;
                    i=i+1;

                }
            });
            if(isok){
                $('#saleprice').text(totalPri*parseInt($("#txtQty7").val()));

                //$("#jia").attr("disabled","disabled");
                //$("#jian").attr("disabled","disabled");

                $('#sale_price').val(totalPri);
            }

            //当前日期的毫秒数 + 天数 * 一天的毫秒数 edit by jiangh
            var d = new Date(ydsj[ydsj.length-1]);
            var n = d.getTime() + 1 * 24 * 60 * 60 * 1000;
            var result = new Date(n);
            var next=result.getFullYear() + "-" + (result.getMonth() + 1) + "-" + result.getDate();
            ydsj[ydsj.length]=next;
            //if(ydsj.length<2){
            //	alert("请确认已经选择了入住日期和离店日期");
            //	return false;
            //}

            if(ydsj.length&&isok){

                var dateinfo="";
                for(var k=0;k<ydsj.length;k++){
                    dateinfo+=ydsj[k].replace('/','-').replace('/','-')+"  ";
                }

                var daynum=DateDiff(ydsj[0].replace('/','-').replace('/','-'),ydsj[ydsj.length-1].replace('/','-').replace('/','-'));
                if(daynum!=ydsj.length){
                    alert("不能隔天预定房间，如有需要请分俩次预定!");
                    dateinfo="";
                    $('#SaleDate').val(dateinfo);
                }else{
                    //var date = new Date(ydsj[ydsj.length-1]);
                    //date.setDate(date.getDate() + 1);//这里的60就是你要加的天数，减也可以。年、月会相应加上去，值得注意的是date.getMonth()得到的月份比实际月份小1，所以实际月份是(date.getMonth()+1)
                    //$('#SaleDate').val(ydsj[0].replace('/','-').replace('/','-')+" 到 "+date.getFullYear() +"-"+ (date.getMonth()+1) +"-"+ date.getDate());//整体时间
                    if(ydsj[0].replace('/','-').replace('/','-')==ydsj[ydsj.length-2].replace('/','-').replace('/','-')){
                        alert("离店日期未选择");
                        $('#SaleDate').val("");
                        $('#dayNum').html("");
                        return false;
                    }

                    $('#SaleDate').val(ydsj[0].replace('/','-').replace('/','-')+" 到 "+ydsj[ydsj.length-2].replace('/','-').replace('/','-'));//整体时间
                }

                $('#strdate').val(ydsj[0].replace('/','-').replace('/','-'));//第一天时间
            }else{
                $('#SaleDate').val("");
            }

            ydsj.pop();// 移除最後一元素 edit by jiangh
            $('#cdays').val(ydsj);//时间
            $('#sjc').val(sjc);//js时间戳
            if(sjc.length){
                $('#days').val(sjc.length);//预定天数赋值
            }else{
                $('#days').val("1");
                tsarr[0] = "1";//没有选择销售计划时不能限制数量加减
            }
            //$('#allprice').text((parseFloat($('#SalePricedj').val())*parseFloat($('#days').val())).toFixed(2));//计算总价
            //$('#orderTotal').text((parseFloat($('#SalePricedj').val())*parseFloat($('#days').val())).toFixed(2));//计算总价

            tsarr = tsarr.sort(function(a,b){//排序房间数量升序
                return a-b;
            });
            $('#txtQty7').val('1');//重新选择销售计划后重置数量
            $('#quantity').val('1');//重新选择销售计划后重置数量(测试)
            $(".month").hide();//隐藏销售计划
        });
    })


}